package pc

import (
	"fmt"
	"net/url"
	"strings"
	"tcsc/models"
	"tcsc/sword"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
)

// "sword"

type Login struct {
	BaseController
}

func (c *Login) Get() {
	if c.GetSession("pc") == nil {
		c.TplName = "pc/login/login.html"
	} else {
		c.Ctx.Redirect(302, "/my")
	}
}
func (c *Login) Post() {
	// shopId := ""
	currentcity := c.GetSession("city")
	username := c.GetString("mobile")
	password := c.GetString("password")
	city := c.GetString("city")
	if c.GetSession("city") == nil {
		c.SetSession("city", city)
	}
	code := c.GetString("code")
	passwordmd5 := sword.ToMD5(password)
	style := c.GetString("style")
	addtime := sword.Gettimes("")
	addr := strings.Split(c.Ctx.Request.RemoteAddr, ":")[0]
	if style == "0" {
		if is := models.Query(`select id,password,city from mt_member where mobile='` + username + `' and status=1`); is != nil {
			passwordsql := fmt.Sprint(is[0]["password"])
			if passwordmd5 == passwordsql {
				c.Data["json"] = 1
				if err := models.Exec(fmt.Sprintf(`update mt_member set logintime='%v',loginip='%v',loginnumber=loginnumber+1 where id=%v`, addtime, addr, is[0]["id"])); err != nil {
					beego.Debug(err)
				}
				if currentcity == nil {
					// if city == "" {
					// 	if is[0]["city"] != nil && is[0]["city"] != "台州" {
					// 		if cityCode := models.Query(`select code from mt_area where name like '%?%'`, fmt.Sprint(is[0]["city"])); cityCode != nil {
					// 			if shop := models.Query(`select id from mt_shop where style = 1 and status = 1 and censoring = 1 and city = ?`, cityCode[0]["code"]); shop != nil {
					// 				shopId = fmt.Sprint(shop[0]["id"])
					// 			}
					// 		}
					// 	}
					// } else if city == "台州市" {
					// 	shopId = ""
					// } else {
					// 	if cityCode := models.Query(`select code from mt_area where name = ?`, city); cityCode != nil {
					// 		if shop := models.Query(`select id from mt_shop where style = 1 and status = 1 and censoring = 1 and city = ?`, cityCode[0]["code"]); shop != nil {
					// 			shopId = fmt.Sprint(shop[0]["id"])
					// 		}
					// 	}
					// }
					// c.SetSession("shopId", shopId)
				}
				c.SetSession("pc", is[0]["id"])
			} else {
				c.Data["json"] = 0 //密码错误
			}
		} else {
			c.Data["json"] = 3 //用户名不存在
		}
	} else {
		if smsresult := models.Query(`select addtime from mt_smssend where type=0 and code='` + code + `' and mobile='` + username + `' order by addtime desc`); smsresult != nil {
			addtime := fmt.Sprint(smsresult[0]["addtime"])
			loc, _ := time.LoadLocation("Local")
			timer, _ := time.ParseInLocation(Tparse, addtime, loc)
			timen := time.Now().Local()
			timer.Add(15 * time.Minute)
			if timer.Before(timen) {
				if is := models.Query(`select id,city from mt_member where mobile='` + username + `' and status=1`); is == nil {

					c.Data["json"] = 2
				} else {
					if currentcity == nil {
						// if city == "" {
						// 	if is[0]["city"] != nil && is[0]["city"] != "台州" {
						// 		if cityCode := models.Query(`select code from mt_area where name like '%?%'`, fmt.Sprint(is[0]["city"])); cityCode != nil {
						// 			if shop := models.Query(`select id from mt_shop where style = 1 and status = 1 and censoring = 1 and city = ?`, cityCode[0]["code"]); shop != nil {
						// 				shopId = fmt.Sprint(shop[0]["id"])
						// 			}
						// 		}
						// 	}
						// } else if city == "台州市" {
						// 	shopId = ""
						// } else {
						// 	if cityCode := models.Query(`select code from mt_area where name = ?`, city); cityCode != nil {
						// 		if shop := models.Query(`select id from mt_shop where style = 1 and status = 1 and censoring = 1 and city = ?`, cityCode[0]["code"]); shop != nil {
						// 			shopId = fmt.Sprint(shop[0]["id"])
						// 		}
						// 	}
						// }
						// c.SetSession("shopId", shopId)
					}
					c.SetSession("pc", is[0]["id"].(string))
					c.Data["json"] = 1
					if err := models.Exec(fmt.Sprintf(`update mt_member set logintime='%v',loginip='%v',loginnumber=loginnumber+1 where id=%v`, addtime, addr, is[0]["id"])); err != nil {
						beego.Debug(err)
					}
				}
			} else {

				c.Data["json"] = 2 //验证码
			}
		} else {

			c.Data["json"] = 2 //验证码错误
		}
	}

	c.ServeJSON()
}

var (
	Web_appid  = beego.AppConfig.String("web_appid")
	Url        = beego.AppConfig.String("url")
	Web_secret = beego.AppConfig.String("web_secret")
)

type Token1 struct {
	Access_token  string `json:"access_token"`
	Expires_in    int    `json:"expires_in"`
	Refresh_token string `json:"refresh_token"`
	Openid        string `json:"openid"`
	Scope         string `json:"scope"`
	Errcode       string `json:"errcode"`
	Errmsg        string `json:"errmsg"`
}

type User1 struct {
	Openid     string        `json:"openid"`
	Nickname   string        `json:"nickname"`
	Sex        int           `json:"sex"`
	Country    string        `json:"country"`
	Province   string        `json:"province"`
	City       string        `json:"city"`
	Headimgurl string        `json:"headimgurl"`
	Privilege  []interface{} `json:"privilege"`
	Unionid    string        `json:"unionid"`
	Errcode    string        `json:"errcode"`
	Errmsg     string        `json:"errmsg"`
}
type LoginWechat struct {
	BaseController
}

func (c *LoginWechat) Get() {
	if c.GetSession("city") == nil {
		if c.GetString("city") != "" {
			c.SetSession("loginCity", c.GetString("city"))
		}
	}
	c.EnableRender = false
	redirect_uri := url.QueryEscape(fmt.Sprintf("https://www.tongcaigou.com"+"/login_wechat_callback?url=%v", c.GetString("url")))
	c.Ctx.Redirect(302, `https://open.weixin.qq.com/connect/qrconnect?appid=`+Web_appid+`&redirect_uri=`+redirect_uri+`&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect`)
}

type LoginWechatCallback struct {
	BaseController
}

func (c *LoginWechatCallback) Get() {
	c.EnableRender = false
	code := c.GetString("code")
	token_url := `https://api.weixin.qq.com/sns/oauth2/access_token?appid=` + Web_appid + `&secret=` + Web_secret + `&code=` + code + `&grant_type=authorization_code`
	req1 := httplib.Get(token_url)
	m1 := new(Token1)
	req1.ToJSON(&m1)
	if m1.Errcode != "" {
		c.Data["json"] = m1
		c.ServeJSON()
	}
	access_token_url := "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + Web_appid + "&grant_type=refresh_token&refresh_token=" + m1.Refresh_token
	req2 := httplib.Get(access_token_url)
	m2 := new(Token1)
	req2.ToJSON(&m2)
	if m2.Errcode != "" {
		c.Data["json"] = m2
		c.ServeJSON()
	}
	user_info_url := "https://api.weixin.qq.com/sns/userinfo?access_token=" + m2.Access_token + "&openid=" + m2.Openid
	req3 := httplib.Get(user_info_url)
	m3 := new(User1)
	req3.ToJSON(&m3)
	if m3.Errcode != "" {
		c.Data["json"] = m3
		c.ServeJSON()
	}
	// utils.Display("m", m3)
	member := models.Query("select id,mobile,city from mt_member where wx_unionid='" + m3.Unionid + "' and status=1 limit 1")
	// utils.Display("mem", m3)
	addtime := sword.Gettimes("")
	addr := strings.Split(c.Ctx.Request.RemoteAddr, ":")[0]
	if member == nil {
		var avatar int64
		if len(m3.Headimgurl) > 3 {
			req4 := httplib.Get(m3.Headimgurl)
			if err := req4.ToFile(`static/avatar/` + m3.Unionid + `.jpg`); err != nil {
				beego.Debug(err)
			} else {
				var resources models.Mt_resources
				resources.Addtime = sword.Timeget()
				resources.Ip = addr
				resources.Name = m3.Unionid + `.jpg`
				resources.Path = `/static/avatar/`
				resources.Pathname = `/static/avatar/` + m3.Unionid + `.jpg`
				resources.Type = 0
				if avatar, err = models.Orm().Insert(&resources); err != nil {
					beego.Debug(err)
				}
			}
		}
		m3.Nickname = sword.FilterEmoji(m3.Nickname)
		shareuid := "0"
		var sid = "0"
		if pro := models.Query(`select code from mt_area where name like '%` + m3.Province + `%'`); pro != nil {
			scode := fmt.Sprint(pro[0]["code"])
			if smem := models.Query(`select id from mt_member where service=1 and servicearea like '%,` + scode + `,%'`); smem != nil {
				sid = smem[0]["id"].(string)
			}
		}
		sql := fmt.Sprintf(`insert into mt_member_wechat(uid,avatar,monicker,sex,addtime,addip,logintime,loginip,wx_unionid,wx_openid_web,country,province,city,sid) values(
				'%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v')`, shareuid, avatar, m3.Nickname, m3.Sex, addtime, addr, addtime, addr,
			m3.Unionid, m3.Openid, m3.Country, m3.Province, m3.City, sid)
		if res, err := models.Orm().Raw(sql).Exec(); err != nil {
			beego.Debug(err)
		} else {
			if uidi, err := res.LastInsertId(); err != nil {
				beego.Debug(err)
			} else {
				c.SetSession("pcwait", fmt.Sprint(uidi))
				c.Ctx.Redirect(302, "/sign")
			}
		}
	} else {
		// shopId := ""
		// city := ""
		currentcity := c.GetSession("city")
		models.Exec("update mt_member set logintime='" + addtime + "',loginip='" + addr + "',loginnumber=loginnumber+1,wx_openid_web='" + m3.Openid + "' where wx_unionid='" + m3.Unionid + "'")
		// beego.Debug("--------------city:", city)
		if currentcity == nil {
			// if loginCity := c.GetSession("loginCity"); loginCity != nil {
			// 	c.SetSession("city", city)
			// 	city = fmt.Sprint(loginCity)
			// 	c.DelSession("loginCity")
			// }
			// if city == "" {
			// 	if member[0]["city"] != nil && member[0]["city"] != "台州" {
			// 		if cityCode := models.Query(`select code from mt_area where name like '%?%'`, fmt.Sprint(member[0]["city"])); cityCode != nil {
			// 			if shop := models.Query(`select id from mt_shop where style = 1 and status = 1 and censoring = 1 and city = ?`, cityCode[0]["code"]); shop != nil {
			// 				shopId = fmt.Sprint(shop[0]["id"])
			// 			}
			// 		}
			// 	}
			// } else if city == "台州市" {
			// 	shopId = ""
			// } else {
			// 	if cityCode := models.Query(`select code from mt_area where name = ?`, city); cityCode != nil {
			// 		if shop := models.Query(`select id from mt_shop where style = 1 and status = 1 and censoring = 1 and city = ?`, cityCode[0]["code"]); shop != nil {
			// 			shopId = fmt.Sprint(shop[0]["id"])
			// 		}
			// 	}
			// }
			// c.SetSession("shopId", shopId)
		}
		c.SetSession("pc", member[0]["id"])
		c.Ctx.Redirect(302, "/my")
	}
}

type Sign struct {
	BaseController
}

func (c *Sign) Get() {
	c.Data["s_url"] = c.Ctx.Request.Host + c.Ctx.Request.RequestURI
	if c.GetSession("pcwait") != nil {
		c.Data["s_title"] = `验证手机`
	} else {
		c.Data["s_title"] = `注册`
	}
	c.TplName = "pc/login/sign.html"
}

type Logout struct {
	BaseController
}

func (c *Logout) Get() {
	c.DelSession("shopId")
	c.DelSession("pc")
	c.Ctx.Redirect(302, "/")
}
func (c *Sign) Post() {
	defer c.ServeJSON()

	wechatwait := c.GetSession("pcwait")
	var id string
	if wechatwait != nil {
		id = wechatwait.(string)
	}
	mobile := c.GetString("mobile")
	password := c.GetString("password")
	code := c.GetString("code")

	if smsresult := models.Query(`select addtime from mt_smssend where type=1 and code='` + code + `' and mobile='` + mobile + `' order by addtime desc`); smsresult != nil {
		addtime := fmt.Sprint(smsresult[0]["addtime"])
		loc, _ := time.LoadLocation("Local")
		timer, _ := time.ParseInLocation(Tparse, addtime, loc)
		timen := time.Now().Local()
		timer = timer.Add(15 * time.Minute)
		if timer.After(timen) {
			if id == "" {
				var shareuid string
				if c.GetSession("share_uid") == nil {
					shareuid = "0"
				} else {
					shareuid = c.GetSession("share_uid").(string)
					if t := models.Query(`select type from mt_member where id=` + shareuid); t != nil {
						if fmt.Sprint(t[0]["type"]) == "0" {
							shareuid = "0"
						}
					}
				}
				if is := models.Query(`select id from mt_member where mobile='` + mobile + `' and status=1`); is != nil {
					c.Data["json"] = 2 //已注册
				} else {
					addtime := sword.Gettimes("")
					addr := strings.Split(c.Ctx.Request.RemoteAddr, ":")[0]
					now := time.Now()
					monicker := fmt.Sprintf(`TCSC%v%v%v%v`, now.Year(), int(now.Month()), now.Day(), sword.RandStr(2))
					sql := fmt.Sprintf(`insert into mt_member(uid,monicker,mobile,addtime,addip,logintime,loginip,password) values(
				'%v','%v','%v','%v','%v','%v','%v','%v')`, shareuid, monicker, mobile, addtime, addr, addtime, addr, sword.ToMD5(password))

					if res, err := models.Orm().Raw(sql).Exec(); err != nil {
						beego.Debug(err)
						c.Data["json"] = 0
					} else {
						if uidi, err := res.LastInsertId(); err != nil {
							beego.Debug(err)
							c.Data["json"] = 0
						} else {
							c.SetSession("wechat", fmt.Sprint(uidi))
							c.Data["json"] = 1
						}
					}
				}
			} else {
				if is := models.Query(`select id,wx_unionid,password from mt_member where mobile='` + mobile + `' and status=1`); is != nil {
					c.Data["json"] = 2
					return
				}

				mw := models.Query(`select * from mt_member_wechat where id=` + id)[0]
				if err := models.Exec(fmt.Sprintf(`insert into mt_member 
						(uid,avatar,monicker,sex,addtime,addip,logintime,loginip,wx_unionid,wx_openid_xapp,
							wx_openid_gzh,country,province,city,sid,password,mobile) 
						values('%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v')`,
					mw["uid"], mw["avatar"], mw["monicker"], mw["sex"], mw["addtime"], mw["addip"], mw["logintime"],
					mw["loginip"], mw["wx_unionid"], mw["wx_openid_xapp"], mw["wx_openid_gzh"], mw["country"],
					mw["province"], mw["city"], mw["sid"], sword.ToMD5(password), mobile)); err != nil {
					c.Data["json"] = 0
					beego.Debug(err)
				} else {
					c.Data["json"] = 1
				}
			}
		} else {
			c.Data["json"] = 3 //验证码过期
		}
	} else {
		c.Data["json"] = 3 //验证码错误
	}
}
